﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.Business.Constants;
using StoreTransport.Business.Helper;
using StoreTransport.DAO;
using StoreTransport.Data;
using StoreTransport.Resources;

namespace StoreTransport.Presentation.Forms {
    public partial class MarketListForm : Form {
        int id = 0;
        Dictionary<string, Dictionary<string, string>> regionDic = new Dictionary<string,Dictionary<string,string>>();
        Dictionary<string, string> areaDic = new Dictionary<string,string>();
        Dictionary<string, string> marketKindDic = new Dictionary<string,string>();
        public MarketListForm() {
            InitializeComponent();
        }

        private void MarketList_Load(object sender, EventArgs e) {
            _tbxMarketCode.Select();
            CommonHelper.SetValueForComboBox(_drpMarketStatus, CommonConstant.Status);
            CommonHelper.SetValueForComboBox(_drpMarketType, CommonConstant.MarketType);
            CommonHelper.SetValueForComboBox(_drpShipmentDay, CommonConstant.ShipmentDay);
            _drpRegion.ValueMember = ColumnName.ID;
            _drpRegion.DisplayMember = ColumnName.RegionName;
            StoreTransportDataContext context = CommonHelper.GetContext();
            _drpRegion.DataSource = context.Regions.OrderBy(c => c.RegionName);

            _drpKind.ValueMember = ColumnName.ID;
            _drpKind.DisplayMember = ColumnName.MarketKindName;
            _drpKind.DataSource = context.MarketKinds.OrderBy(c => c.MarketKindName);
            marketKindDic = context.MarketKinds.ToDictionary(c => c.ID.ToString(), c => c.MarketKindName);

            _drpAreaList.ValueMember = ColumnName.Value;
            _drpAreaList.DisplayMember = ColumnName.Text;
            if (context.Regions.Count() > 0) {
                var areas = context.Regions.OrderBy(c => c.RegionName).First().Areas;
                foreach (var area in areas) {
                    _drpAreaList.Items.Add(new ComboBoxItem(area.ID.ToString(), area.AreaName));
                    if (_drpAreaList.Items.Count > 0) {
                        _drpAreaList.SelectedIndex = 0;
                    }
                }
                var areaList = context.Areas;
                areaDic = context.Areas.ToDictionary(c => c.ID.ToString(), c => c.AreaName);
                foreach (var area in areaList) {
                    string regionName = area.Region1.RegionName;
                    if (!regionDic.ContainsKey(regionName)) {
                        regionDic.Add(regionName, new Dictionary<string, string>());
                    }
                    regionDic[regionName].Add(area.ID.ToString(), area.AreaName);
                }
            }
            LoadMarkets();
        }

        private void LoadMarkets() {
            _grdMarket.AutoGenerateColumns = false;
            IEnumerable<Market> marketList = null;
            StoreTransportDataContext context = CommonHelper.GetContext();
            if (_cbxShowInvalidMarket.Checked) {
                var invalidChar = ValidData.I.ToString()[0];
                marketList = context.Markets.Where(c => c.ValidData.Equals(invalidChar)).Cast<Market>();
            } else {
                marketList = context.Markets.Cast<Market>();
            }
            marketList = marketList.OrderBy(c => c.Status).
                ThenBy(c => c.Type).ThenBy(c => c.MarketName);
            List<PresentMarketDTO> presentMarketList = new List<PresentMarketDTO>();
            foreach (Market m in marketList) {
                PresentMarketDTO pm = new PresentMarketDTO(m.ID, string.Empty, m.MarketName);
                pm.Status = CommonHelper.GetEnumValue(m.Status, CommonConstant.StatusDic);
                pm.Type = CommonHelper.GetEnumValue(m.Type, CommonConstant.MarketTypeDic);
                pm.TransportDay = CommonHelper.GetEnumValue(m.TransportDay, CommonConstant.ShipmentDayDic);
                pm.MarketCode = m.MarketCode == null ? string.Empty : m.MarketCode; 
                if (m.Area != null && areaDic.ContainsKey(m.Area.ToString())) {
                    pm.Area = areaDic[m.Area.ToString()];
                }
                if (m.MarketKind != null && marketKindDic.ContainsKey(m.MarketKind.ID.ToString())) {
                    pm.Kind = marketKindDic[m.Kind.ToString()];
                }
                presentMarketList.Add(pm);
            }
            _grdMarket.DataSource = presentMarketList.OrderBy(c => c.Status).
                ThenBy(c => c.TransportDay).ThenBy(c => c.Area).ThenBy(c => c.MarketName).ToList();
        }

        private void _btnDelete_Click(object sender, EventArgs e) {
            if (_grdMarket.SelectedRows.Count > 0) {
                DialogResult result = MessageBox.Show(StoreTransportResource.Message_ConfirmDelete,
                    StoreTransportResource.MessageBox_ConfirmDelete, MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes) {
                    try {
                        StoreTransportDataContext context = CommonHelper.GetContext();
                        foreach (DataGridViewRow row in _grdMarket.SelectedRows) {
                            id = int.Parse(row.Cells[0].Value.ToString());
                            Market selectedItem = context.Markets.Where(c => c.ID == id).First();
                            context.Markets.DeleteOnSubmit(selectedItem);
                            context.SubmitChanges();
                        }
                        LoadMarkets();
                        id = 0;
                    } catch (Exception ex) {
                        MessageBox.Show(StoreTransportResource.ErrorMessage_CanNotDeleteItem);
                    }
                }
            } else {
                MessageBox.Show(StoreTransportResource.NoItemSelected);
            }
        }

        private void _btxCreate_Click(object sender, EventArgs e) {
            _tbxMarketCode.Select();
            _lblID.Text = StoreTransportResource.Form_NewID;
            _tbxMarketCode.Text = string.Empty;
            _tbxMarketCode.ReadOnly = false;
            _tbxMarketName.Text = string.Empty;
            CommonHelper.ResetCombobox(_drpKind);
            CommonHelper.ResetCombobox(_drpMarketStatus);
            CommonHelper.ResetCombobox(_drpMarketType);
            CommonHelper.ResetCombobox(_drpShipmentDay);
            CommonHelper.ResetCombobox(_drpRegion);
            if (_drpRegion.Items.Count > 0) {
                LoadAreaList(_drpRegion.Text);
            }
            id = 0;
        }

        private void _btxSave_Click(object sender, EventArgs e) {
            string errorMessage = CommonHelper.CheckRequiredField(_tbxMarketCode.Text, _lblMarketCode.Text);
            errorMessage += CommonHelper.CheckRequiredField(_tbxMarketName.Text, _lblMarketName.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage, StoreTransportResource.ErrorMessage_ErrorMessageTitle);
                return;
            }
            Market market = null;
            StoreTransportDataContext context = CommonHelper.GetContext();
            if (id == 0) {
                if (context.Markets.FirstOrDefault(c => c.MarketName.Equals(_tbxMarketName.Text)) != null) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_Market, _tbxMarketName.Text));
                    return;
                }
                market = new Market();
                context.Markets.InsertOnSubmit(market);
            } else {
                var item = context.Markets.FirstOrDefault(c => c.MarketName.Equals(_tbxMarketName.Text));
                if (item != null && item.ID != id) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_Market, _tbxMarketName.Text));
                    return;
                }
                market = context.Markets.Where(c => c.ID == id).First();
            }
            market.MarketName = _tbxMarketName.Text;
            market.MarketCode = _tbxMarketCode.Text;
            market.Type = _drpMarketType.SelectedValue.ToString()[0];
            market.Status = _drpMarketStatus.SelectedValue.ToString()[0];
            market.Kind = int.Parse(_drpKind.SelectedValue.ToString());
            market.TransportDay = int.Parse(_drpShipmentDay.SelectedValue.ToString());
            market.Area = int.Parse((_drpAreaList.SelectedItem as ComboBoxItem).Value);
            market.ValidData = ValidData.V.ToString()[0];
            context.SubmitChanges();
            LoadMarkets();
        }

        private void _btxEdit_Click(object sender, EventArgs e) {
            if (_grdMarket.SelectedRows.Count > 0) {
                id = int.Parse(_grdMarket.SelectedRows[0].Cells[0].Value.ToString());
                EditItem();
            }
        }

        private void EditItem() {
            Market selectedItem = CommonHelper.GetContext().Markets.Where(c => c.ID.Equals(id)).First();
            _lblID.Text = id.ToString();
            CommonHelper.SetComboboxValue(_drpMarketStatus, selectedItem.Status.ToString());
            CommonHelper.SetComboboxValue(_drpMarketType, selectedItem.Type.ToString());
            CommonHelper.SetComboboxValue(_drpShipmentDay, selectedItem.TransportDay.ToString());
            if (selectedItem.Area != null) {
                CommonHelper.SetComboboxValue(_drpRegion, selectedItem.Area1.Region);
                LoadAreaList(selectedItem.Area1.Region1.RegionName);
                //CommonHelper.SetComboboxValue(_drpAreaList, selectedItem.Area.ToString());
                _drpAreaList.SelectedItem = _drpAreaList.Items.Cast<ComboBoxItem>()
                    .Where(c => c.Value.Equals(selectedItem.Area.ToString())).First();
            }
            CommonHelper.SetComboboxValue(_drpKind, selectedItem.Kind);
            _tbxMarketName.Text = selectedItem.MarketName;
            _tbxMarketCode.Text = selectedItem.MarketCode;
            _tbxMarketCode.ReadOnly = true;
            _lblID.Text = id.ToString();
        }

        private void _drpRegion_SelectedIndexChanged(object sender, EventArgs e) {
            string selectedRegionName = _drpRegion.Text;
            LoadAreaList(selectedRegionName);
        }

        private void LoadAreaList(string selectedRegionName) {
            if (regionDic.ContainsKey(selectedRegionName)) {
                _drpAreaList.Items.Clear();
                foreach (var area in regionDic[selectedRegionName]) {
                    _drpAreaList.Items.Add(new ComboBoxItem(area.Key, area.Value));
                }
                if (_drpAreaList.Items.Count > 0) {
                    _drpAreaList.SelectedIndex = 0;
                }
            }
        }

        private void _btnRefreshList_Click(object sender, EventArgs e) {
            LoadMarkets();
        }

        private void _grdMarket_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
            id = int.Parse(_grdMarket.Rows[e.RowIndex].Cells[0].Value.ToString());
            EditItem();
        }
    }
}
